package cn.gzsxt.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.gzsxt.po.SysUser;
import cn.gzsxt.service.SysUserService;
import cn.gzsxt.service.impl.SysUserServiceImpl;
import cn.gzsxt.utils.CookieUtils;
import cn.gzsxt.vo.MsgObj;
@WebServlet("/syslogin.gzsxt")
public class SysUserLoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	//引入Service层
	private SysUserService service = new SysUserServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置响应MIME和编码
		resp.setContentType("application/json;charset=utf-8");
		//获取输出流
		PrintWriter out = resp.getWriter();
	
		
		
		//接受账号密码验证码
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String verifyCode = req.getParameter("verifyCode");
		//TODO 正则判断
		
		//1.校验验证码是否和session中四位随机数想匹配
		//1.1获取session中的验证码
		String rand = (String) req.getSession().getAttribute("rand");
		//1.2创建一个错误消息对象
		MsgObj msgObj = null;
		if(!verifyCode.toLowerCase().equals(rand.toLowerCase())){
			System.out.println("验证码错误");
			msgObj = new MsgObj(0, "验证码错误");
			//将对象装换成json对象
		}else{
			//2.调用业务层方法 : ctrl+1 快速接受变量
			SysUser sysUser = service.login(uname, pwd);
			if(sysUser == null){//登录失败
				msgObj = new MsgObj(0, "账号或者密码错误");
			}else{//登录成功
				//登录成功以后,将user对象共享到Cookie中
				//先将User对象转换成json字符串
				String  user2Json = JSON.toJSONString(sysUser);
				//使用CookieUtil工具类将json串以编码的形式使用Cookie保存到本地浏览器
				CookieUtils.setCookie(req, resp, "sysUser", user2Json, 3600, true);
				msgObj = new MsgObj(1, "登录成功");
			}
		}
		String msgObj2Json = JSON.toJSONString(msgObj);
		//将json对象响应到浏览器
		out.print(msgObj2Json);
		out.flush();//强制刷新
		out.close();
	}
}
